<template>
  <div class="login-div">
    <el-card class="box-card">
      <h1>房源管理系统登录</h1>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "login",
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formdata = this.qs.stringify(this.ruleForm);
          axios.post("http://localhost:8000/admins/login",formdata).then((res)=>{
            let data = res.data;
            if (data.state === 20000){
              //设置参数
              localStorage.setItem("jwt",data.data);
              //跳转地址
              this.$router.push("/");
            }else {
              this.$message({
                dangerouslyUseHTMLString: true,
                message: "<strong>"+data.message+"</strong>",
                type: 'error'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
  body{
    background: #909399;
  }
  .login-div{
    width: 600px;
    margin: 50px auto;
    padding: 20px 50px;
    text-align: left;
  }
  .login-div h1{
    margin-bottom: 20px;
    text-align: center;
  }
</style>